# -*- coding = utf-8 -*-
from flask import Flask,jsonify,render_template,request,escape,session, redirect, url_for, flash
from panduan import panduan,log_login
from gaode import geocode,weatherinfo,walking
from reserch import reserch4letters
import os
basedir = os.path.abspath(os.path.dirname(__file__))
li_key="31e2e9ede61f2f81638ca15063de2984"

app = Flask(__name__)
app.secret_key ='asdjfkajdlksfjkajdsf'

@app.before_request
def before_request():
    try:
        print('{}'.format(request.path))
        if 'username' not in session and not any( item for item in ['/login', '/register', '/static'] if item  in request.path) and request.path !='/':
            print('访问{}，未登陆，请先登录...'.format(request.path))
            return redirect(url_for('login'))
    except Exception as e:
        print("有异常 - {}".format(e))

@app.route("/login",methods = ["GET", "POST"])
def login():
    if request.method == "POST":
        zhanghao = request.form["zhanghao"]
        mima = request.form["mima"]
        zhanghao = int(zhanghao)
        mima = int(mima)
        a = panduan(zhanghao,mima)
        if a == "true":
            session['username'] = zhanghao
            return redirect(url_for("index"))
        else:
            return render_template("Login.html",loginfail = "登录失败")
    else:
        return render_template("Login.html")

@app.route("/logout", methods = ["GET", "POST"])
def logout():
    # flash('已退出，欢迎下次再来！')
    session.pop('username', None)
    return redirect(url_for('index'))

@app.route("/",methods = ["GET"])
def index():
    return render_template("index.html")


@app.route("/register",methods=['GET','POST'])
def register():
    if request.method == 'POST':
        zhanghao= request.form["zhanghao"]
        mima = request.form["mima"]
        log_login(zhanghao,mima)
        return render_template("Logon.html")
    else:
        return render_template("Logon.html")


@app.route('/name')
def name():
    return render_template('name.html')

@app.route('/fullname',methods=['POST'])
def fullname():
    # 接收数据：request.form[HTML-参数名称]
    py_firstname = request.form['firstname']
    py_lastname = request.form['lastname']
    py_fullname = py_firstname.title()+' '+py_lastname.title()

    return render_template('fullname.html',
                            firstname = py_firstname,
                            lastname = py_lastname,
                            fullname = py_fullname)

@app.route('/tongji')
def tongji():
    return render_template('tongji.html')

@app.route('/tongji_result',methods=['POST'])
def tongji_result():
    # 接收数据：request.form[HTML-参数名称]
    # 1. 名字的全称（完整的应用）：用户输入数据--->后端接收数据--->后端处理数据--->返回到HTML页面
    # 2. 元音字母查询（第二个功能）
    # 3. 自选：购物车 或者 课程表
    # py_firstname = request.form['firstname']
    # py_lastname = request.form['lastname']
    # py_fullname = py_firstname.title()+' '+py_lastname.title()
    # 在 中央登记中心，写这么多 python过程的代码 是不是有点不好玩？
    # 使用模块来写函数过程，在视图函数中调用模块实现函数方法
    py_word = request.form['word']
    py_vowels = request.form['vowels']
    py_found = reserch4letters(py_vowels,py_word)

    return render_template('tongji_result.html',
                            word = py_word,
                            vowels = py_vowels,
                            found = py_found)


@app.route("/weather",methods = ["GET", "POST"])
def weather():
    if request.method == 'POST':
        maincity = request.form["city"]
        tianqi = weatherinfo(maincity)
        province1 = tianqi["lives"][0]['province']
        city1 = tianqi["lives"][0]['city']
        adcode1 = tianqi["lives"][0]['adcode']
        weather1 = tianqi["lives"][0]['weather']
        temperature1 = tianqi["lives"][0]['temperature']
        winddirection1 = tianqi["lives"][0]['winddirection']
        windpower1 = tianqi["lives"][0]['windpower']
        humidity1 = tianqi["lives"][0]['humidity']
        reporttime1 = tianqi["lives"][0]['reporttime']
        return render_template(
            "weather_result.html",
            the_geocode = tianqi,
            province = province1,
            city = city1,
            adcode = adcode1,
            weather = weather1,
            temperature = temperature1,
            winddirection = winddirection1,
            windpower = windpower1,
            humidity = humidity1,
            reporttime = reporttime1
            )
    return render_template("weather.html")


@app.route("/searchway",methods = ["GET","POST"])
def searchway():
    if request.method == 'POST':
        result = []
        origin = request.form["origin_place"]
        location_origin = geocode(origin)
        destination = request.form["destination_place"]
        location_destination = geocode(destination)
        origin_destination = walking(location_origin,location_destination)
        step_data= origin_destination["route"]["paths"][0]['steps']
        for m in step_data:
            result.append(m["instruction"])
        print(result)
        return render_template(
            "stepway_result.html",
            direct_way = result
        )
    return render_template("step_way.html")





if __name__ == '__main__':
    app.run(debug=True)
